// my/pages/xtxSelfNoPay/xtxSelfNoPay.js
var http = require('../../../utils/https');
Page({
  data: {
    orderId: '',
    countdownTime: 0,
    orderInfo: {
      status: '待付款',
      remainingTime: '16:3',
      pickupPoint: 'xx自提点关谷软件园',
      products: [{
        name: '甜玉米',
        spec: '900g',
        quantity: 1,
        price: 39.00,
        image: '/images/xtxFruit.png'
      }],
      priceDetails: {
        subtotal: 39.00,
        deliveryFee: 0.00,
        discount: 15.00
      },
      orderTime: '2002/05/20 10:00:00',
      orderNumber: '34567890553345433',
      paymentMethod: '微信支付'
    },
    showPayPopup: false,
    paying: false,
    userBalance: '0.00',
    payAmount: '0.00',
    userId: null,
    allOrderIemDetails: [],
    currentOrderData: {},
    couponList: [],
    showItems: true
  },
  onLoad(options) {
    console.log(options);
    this.loadOrder(options.orderId)
    this.loadCoupon();
    if (options.orderId) {
      this.setData({
        orderId: options.orderId
      });
      this.loadOrderDetail(options.orderId);
    }
    this.setData({
      countdownTime: 1800000
    });
  },

  loadOrder(orderId) {
    http.GET(`/order/orders/${orderId}`, {}, (res) => {
      if (res.code == 200) {
        this.setData({
          currentOrderData: res.data
        })
      }
      console.log('加载订单成功:', res);

    }, (err) => {
      console.log('加载订单成功:', res);
    })
  },
  
  onUnload() {
    if (this.data.countdownTimer) {
      clearInterval(this.data.countdownTimer);
    }
  },
  formatPrice(price) {
    return Number(price).toFixed(2);
  },
  loadCoupon() {
    http.GET('/coupon/coupons/list', null, (res) => {
      if (res.code === 200) {
        const couponList = res.rows;
        const current = this.data.currentOrderData;
        if (!current || !current.totalAmount) {
          this.setData({
            couponList
          });
          return;
        }
        const orderTotal = Number(current.totalAmount);
        const eligible = couponList.filter(c => orderTotal >= Number(c.condition));
        let selected = null;
        if (eligible.length > 0) {
          selected = eligible.sort((a, b) => b.amount - a.amount)[0];
          current.couponAmount = Number(selected.amount).toFixed(2);
          this.setData({
            currentOrderData: current
          });
        }
        this.setData({
          couponList: couponList.map(c => ({
            ...c,
            isEligible: orderTotal >= Number(c.condition)
          })),
          selectedCoupon: selected || null
        });
      }
    }, () => {});
  },
  // 加载订单详情
  loadOrderDetail(orderId) {
    http.GET('/order/item/list', {
      orderId
    }, (res) => {
      const formatted = (res.rows || []).map(it => ({
        ...it,
        subtotal: Number(it.subtotal).toFixed(2),
        unitPrice: Number(it.unitPrice).toFixed(2)
      }));
      this.setData({
        allOrderIemDetails: formatted
      });
    }, () => {});
    setTimeout(() => {
      wx.hideLoading();
    }, 500);
  },
  toggleShowItems() {
    this.setData({
      showItems: !this.data.showItems
    });
  },
  getUserIdFromStorage() {
    try {
      let u = wx.getStorageSync('userInfo');
      if (typeof u === 'string') {
        u = JSON.parse(u || '{}');
      }
      return (u && u.userId) || wx.getStorageSync('userId') || null;
    } catch (e) {
      return wx.getStorageSync('userId') || null;
    }
  },
  fetchUserBalance(userId) {
    if (!userId) return;
    http.GET('/api/wallet/balance', {
      userId
    }, (res) => {
      const balance = (res && (res.balance || (res.data && res.data.balance))) || (res && res.total_balance) || (res && res.data && res.data.total_balance);
      this.setData({
        userBalance: this.formatPrice(balance || 0)
      });
    }, () => {});
  },
  fetchOrderPayable(orderId) {
    if (!orderId) return;
    http.GET('/api/orders/payable', {
      orderId
    }, (res) => {
      const amount = (res && (res.total_amount || (res.data && res.data.total_amount))) || (res && res.amount) || (res && res.data && res.data.amount);
      this.setData({
        payAmount: this.formatPrice(amount || 0)
      });
    }, () => {});
  },
  navigateBack() {
    wx.navigateBack({
      delta: 1,
      fail: () => {
        wx.switchTab({
          url: '/pages/my/my'
        });
      }
    });
  },
  cancelOrder() {
    wx.showModal({
      title: '确认取消',
      content: '确定要取消这个订单吗？',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/my/pages/xtxCancelSelf/xtxCancelSelf?orderId=' + this.data.orderId
          });
        }
      }
    });
  },
  payOrder() {
    const userId = this.getUserIdFromStorage();
    this.setData({
      userId
    });
    this.fetchOrderPayable(this.data.orderId);
    this.fetchUserBalance(userId);
    this.setData({
      showPayPopup: true
    });
  },
  onCountDownFinish() {
    wx.showModal({
      title: '订单超时',
      content: '订单已超时，是否重新下单？',
      success: (r) => {
        if (r.confirm) {
          wx.showToast({
            title: '跳转重新下单',
            icon: 'none'
          });
        } else {
          wx.navigateBack();
        }
      }
    });
  },
  closePayPopup() {
    this.setData({
      showPayPopup: false,
      paying: false
    });
  },
  confirmBalancePay() {
    if (this.data.paying) return;
    const userBalance = parseFloat(this.data.userBalance || 0);
    const payAmount = parseFloat(this.data.payAmount || 0);
    if (userBalance < payAmount) {
      wx.showToast({
        title: '余额不足，请充值',
        icon: 'none'
      });
      return;
    }
    this.setData({
      paying: true
    });
    setTimeout(() => {
      this.setData({
        paying: false,
        showPayPopup: false
      });
      wx.showToast({
        title: '支付成功',
        icon: 'success',
        duration: 1200
      });
      wx.navigateTo({
        url: '/shopCart/pages/paysuccess/paysuccess?orderId=' + this.data.orderId
      });
    }, 600);
  }
});